package com.viser.partyinrs.adapters;

import java.util.ArrayList;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONObject;

import com.viser.partyinrs.entities.Post;
import com.viser.partyinrs.http.HttpDispatcher;

public class PostAdapter extends DataAdapter {
	
	public PostAdapter() {
		dispatcher = new HttpDispatcher();
	}
	
	@SuppressWarnings("finally")
	public ArrayList<Post> getPostEntities(String upit) {
		ArrayList<Post> postovi = new ArrayList<Post>();
		try
		{
			String httpResponse = dispatcher.getHttpResponse_GET(pageBase+"postovi_list.php?upit=upit");
			JSONArray postArray = new JSONArray(httpResponse);
			for(int i=0; i<postArray.length(); i++)
			{
				JSONObject post = postArray.getJSONObject(i);
				Post p = new Post();
				p.datumVreme = post.getString("datum_vreme");
				p.geoX = post.getDouble("geo_x");
				p.geoY = post.getDouble("geo_y");
				p.username = post.getString("username");
				p.nazivMesto = post.getString("naziv_mesto");
				p.opis = post.getString("opis");
				p.redniBroj = post.getInt("rb");
				postovi.add(p);
			}
		}
		catch (Exception ex) { }
		finally {
			return postovi;
		}
	}
	
	public boolean dodajPost(String username, String nazivMesta, String opis, double geoX, double geoY)
	{
		boolean rezultat=true;
		
		try {
			Vector<String> postParameters = new Vector<String>();
			postParameters.add("username=" + username);
			postParameters.add("naziv_mesta=" + nazivMesta);
			postParameters.add("opis=" + opis);
			postParameters.add("geo_x=" + geoX);
			postParameters.add("geo_y=" + geoY);
			
			String httpResponse = dispatcher.getHttpResponse_POST(pageBase+"dodajpost.php", postParameters);
			rezultat = httpResponse.trim().equals("1");
		} catch (Exception e) {
			rezultat = false;
		}
		return rezultat;
	}
}
